import Cookie from 'js-cookie'
import getDeviceInfo from './deviceInfo'

export const getInfoCookie = () => {
  let resulte = {}
  let cookie = Cookie.get('ppz_openinfo') || Cookie.get('cqv_openinfo')
  if (cookie) {
    let userInfo = decodeURIComponent(cookie)
    userInfo = decodeURIComponent(userInfo)
    resulte = JSON.parse(userInfo)
  }
  return resulte
}

export const paddingZero = v => {
  if (v < 10) {
    return '0' + v
  } else {
    return v
  }
}

export const openApp = (catid, catName, status, downloadLink, switchPage) => {
  if (!getDeviceInfo().isPhone) {
    // 如果不是手机端 直接返回
    return
  }
  const appUrl = `brandzw://com.shanzhou.brandzw?${catid}&${catName}&${status}&${switchPage}`
  if (getDeviceInfo().isIOS && getDeviceInfo().IOSVersion <= 9) {
    setTimeout(function () {
      const iframe = document.createElement('iframe')
      iframe.src = appUrl
      iframe.style.display = 'none'
      document.body.appendChild(iframe)
    }, 100)
  } else {
    window.location.href = appUrl
  }
  if (downloadLink) {
    setTimeout(function () {
      if (document.hasFocus()) {
        window.location.href = downloadLink
      }
    }, 1000)
  }
}

// 传入要复制内容的dom节点
export const copy = el => {
  const range = document.createRange()
  range.selectNode(el)
  const selection = window.getSelection()
  if (selection.rangeCount > 0) selection.removeAllRanges()
  selection.addRange(range)
  document.execCommand('copy')
}

// 返回不刷新 针对低版本 ios
export const backRefresh = () => {
  if (getDeviceInfo().isIOS) {
    let isPageHide = false
    window.addEventListener('pageshow', function () {
      if (isPageHide) {
        window.location.reload()
      }
    })
    window.addEventListener('pagehide', function () {
      isPageHide = true
    })
  }
}

export const getUrlString = name => {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  let r = window.location.search.substr(1).match(reg)
  if (r != null) return decodeURI(r[2])
  return null
}